package com.example.smart_video.ui.activity;

import static com.example.smart_video.model.Constants.TENCENT_BUCKET_OFFICE_URL;

import androidx.databinding.DataBindingUtil;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.example.cleandemo3.R;
import com.example.cleandemo3.databinding.ActivityDownloadBinding;
import com.example.smart_video.model.Constants;
import com.example.smart_video.utils.AlbumNotifyHelper;
import com.wink_172.library.activity.SmartActivity;
import com.wink_172.library.utils.FileUtil;
import com.wink_172.library.view.ActionBarView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

/**
 * 下载页面
 */
public class DownLoadActivity extends SmartActivity {

    public ActivityDownloadBinding binding;
    private ProgressDialog mProgressDialog;

    public static void startActivity(Context context, Object... args) {
        Intent intent = new Intent(context, DownLoadActivity.class);

        if (args.length > 0) {
            intent.putExtra(com.wink_172.library.model.Constants.PARAM_DATA1, (String) args[0]);
        }

        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_download);
        binding.setOnClickListener(this);

        initView();
        init();
    }

    public void initView() {
        ((ActionBarView) binding.actionBar).updateAllContent(R.mipmap.icon_nav_arrow, "下载页面", "");
        ((ActionBarView) binding.actionBar).setCallback(new ActionBarView.ICallback() {
            @Override
            public void onSendEvent(int event, String content) {
                if (event == ActionBarView.LEFT_BTN) {
                    finish();

                }
            }
        });

        binding.inputView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                binding.statusView.setText("当前无任务");
            }
        });

    }

    private void init() {
        String url = (String) getIntent().getStringExtra(com.wink_172.library.model.Constants.PARAM_DATA1);

        if (!TextUtils.isEmpty(url)) {

                binding.inputView.setText(TENCENT_BUCKET_OFFICE_URL +url);


        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_down:
                downLoadFile();
                break;
        }
    }


    private static final String TAG = "DownLoadActivity";


    /**
     * 下载文件
     * 请注意如果
     * 在onSuccess(File result)  报错
     * 请检查FileProvider
     * 指向本地实际地址
     */
    private void downLoadFile() {
        String input = binding.inputView.getText().toString();

        binding.statusView.setText("正在下载中..");
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
        RequestParams params = new RequestParams(input);
        // 为RequestParams设置文件下载后的保存路径


        //
        final String save_path = Constants.saveSDPath + FileUtil.Companion.getFileUrlName(input);//本地保存绝对路径
        Log.e(TAG, "downLoadFile: ====>>"+save_path );
        params.setSaveFilePath(save_path);

        // 下载完成后自动为文件命名
//        params.setAutoRename(true);

        x.http().get(params, new Callback.ProgressCallback<File>() {

            @Override
            public void onSuccess(File result) {
                com.wink_172.library.utils.CommonUtils.showToast("下载成功");
                binding.statusView.setText("下载成功！！");


                //通知更新图库
                try {
                    MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                    mmr.setDataSource(save_path);
                    int  duration = Integer.parseInt(mmr.extractMetadata
                            (MediaMetadataRetriever.METADATA_KEY_DURATION));
                    AlbumNotifyHelper.insertVideoToMediaStore(x.app(), save_path, 0, duration);
                } catch (Exception e) {
                    e.printStackTrace();
                    AlbumNotifyHelper.insertVideoToMediaStore(x.app(), save_path, 0, 0);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                if(ex.toString().contains("404")){
                    String url = (String) getIntent().getStringExtra(com.wink_172.library.model.Constants.PARAM_DATA1);
                    binding.inputView.setText(TENCENT_BUCKET_OFFICE_URL +url);
                    com.wink_172.library.utils.CommonUtils.showToast("下载失败,为您手动切换链路资源地址");

                }else {
                    com.wink_172.library.utils.CommonUtils.showToast("下载失败");
                    binding.statusView.setText("下载失败！！"+ex.getMessage()+ex.toString());
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                Log.e(TAG, "onFinished: ====>>");
                mProgressDialog.dismiss();

            }

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                // 当前的下载进度和文件总大小
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setMessage("正在下载中......");
                mProgressDialog.show();
                mProgressDialog.setMax((int) total);
                mProgressDialog.setProgress((int) current);
            }
        });

    }
}